<template>
	<view>
		<button @click="initBluetooth">初始化蓝牙并搜索设备</button>
		<view class="device-list">
			<view v-for="(device, index) in deviceList" :key="index" class="device-item">
				设备名称: {{ device.deviceName }} - 设备ID: {{ device.deviceId }} - 信号强度: {{ device.rssi }} - UUID:
				{{device.advertisServiceUUIDs}} - 是否可连接: {{device.connectable}}
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				deviceList: [] // 存储搜索到的蓝牙设备列表
			};
		},
		methods: {
			// 初始化蓝牙并搜索设备
			initBluetooth() {
				this.openBluetoothAdapter();
			},
			// 打开蓝牙功能
			openBluetoothAdapter() {
				wx.openBluetoothAdapter({
					success: () => {
						console.log('蓝牙模块已初始化');
						this.startSearch(); // 确保startSearch方法存在
					},
					fail: (err) => {
						console.error('初始化蓝牙失败', err);
						wx.showToast({
							title: '初始化蓝牙失败',
							icon: 'none'
						});
					}
				});
			},
			// 开始搜索蓝牙设备
			startSearch() {
				wx.startBluetoothDevicesDiscovery({
					allowDuplicatesKey: true, // 允许重复上报同一设备
					success: () => {
						console.log('开始搜索蓝牙设备');
					},
					fail: (err) => {
						console.error('搜索蓝牙设备失败', err);
						wx.showToast({
							title: '搜索蓝牙设备失败',
							icon: 'none'
						});
					}
				});
			},
			// 监听搜索到新设备的事件
			onBluetoothDeviceFound(device) {
				// console.log(device.devices);
				if (device.devices && device.devices.length > 0) {
					const newDeviceInfo = {
						deviceName: device.devices[0].localName || '未知设备',
						deviceId: device.devices[0].deviceId,
						rssi: device.devices[0].RSSI || '无信号强度信息',
						advertisServiceUUIDs: device.devices[0].advertisServiceUUIDs && device.devices[0].advertisServiceUUIDs[0] || "UUID未知",
						connectable: device.devices[0].connectable ? device.devices[0].connectable : '未知'
					};
					
					// 检查列表中是否已经存在该设备
					const exists = this.deviceList.some((existingDevice) => {
						return existingDevice.deviceName === newDeviceInfo.deviceName && existingDevice.advertisServiceUUIDs === newDeviceInfo.advertisServiceUUIDs;
					});
					
					// 如果不存在，则添加到列表中
					if (!exists) {
						this.deviceList.push(newDeviceInfo);
					}
				}
			}
		},
		// 页面加载时注册蓝牙设备搜索事件
		onLoad() {
			wx.onBluetoothDeviceFound(this.onBluetoothDeviceFound);
		},
		// 页面卸载时注销蓝牙设备搜索事件
		onUnload() {
			wx.offBluetoothDeviceFound();
			wx.stopBluetoothDevicesDiscovery({
				success: () => {
					console.log('停止蓝牙搜索');
				}
			});
		}
	};
</script>

<style scoped>
	.device-list {
		margin-top: 20px;
	}

	.device-item {
		background-color: #f0f0f0;
		padding: 10px;
		border-bottom: 1px solid #ddd;
	}
</style>
